package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.to.es.SkuHasStock;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import jdk.nashorn.internal.ir.CallNode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService imagesService;

    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SearchFeignService searchFeignService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * //TODO 高级部分完善
     *
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        // 保存 基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        // 保存 商品描述图集
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 保存 展示图集
        List<String> images = vo.getImages();
        imagesService.saveSpuInfoImages(spuInfoEntity.getId(), images);
        // 保存 商品的基本属性
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());

        attrValueService.saveBatch(collect);

        // 远程保存 购买该商品 的积分信息
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        couponFeignService.saveBoundInfo(spuBoundTo);

        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() != 0) {
            // sku 保存相关信息  对于这个skus是封装了 要操作 3张表的数据 所以进行一个整体遍历 就不能用的流的操作
            skus.forEach((sku) -> {
                // 获取每一个 sku的默认图片
                List<Images> skuImages = sku.getImages();
                String defaultImageUrl = "";
                for (Images image : skuImages) {
                    if (image.getDefaultImg() == 1) {
                        defaultImageUrl = image.getImgUrl();
                    }
                }
                // 保存 sku的基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0l);
                skuInfoEntity.setSkuDefaultImg(defaultImageUrl);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoService.save(skuInfoEntity);

                // 保存 sku对应的图片信息表
                List<Images> imagesList = sku.getImages();
                List<SkuImagesEntity> skuImagesEntityList = imagesList.stream().map((image) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                }).filter((image) ->
                        // 过滤掉 图片 为空 的 sku-image行数据
                        !StringUtils.isEmpty(image.getImgUrl())
                ).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);

                // 保存 sku的销售属性
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntityList = attrs.stream().map((attr) -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntityList);

                // 保存 满减（满了多少件  满了多少钱）  以及 会员价格
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                // 只有 满减金额 大于0 或者 购买数大于0
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getDiscount().compareTo(new BigDecimal("0")) == 1) {
                    couponFeignService.saveFullReduceInfo(skuReductionTo);
                }

            });


        }

    }


    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            /**
             *  status=1 and (id=1 or spu_name like xxx)  如果没有这个 and 这个括号就会括起来 查询的数据就会不对
             */
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        //
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        // 只有 id 大于 0 才拼接
        if (!StringUtils.isEmpty(brandId) && Integer.parseInt(brandId) > 0) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && Integer.parseInt(catelogId) > 0) {
            wrapper.eq("catalog_id", catelogId);
        }

        /**
         * status: 2
         * key:
         * brandId: 9
         * catelogId: 225
         */

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架   最总会保存在 es中
     *
     * @param spuId
     */
    @Override
    public void upSpu(Long spuId) {
        //1.0  查出 该spu 相关的所有的 规格属性
        List<ProductAttrValueEntity> baseAttrs = attrValueService
                .list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        List<Long> attrIds = baseAttrs.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        // 得出 上架商品 的规格属性 并且符合 检索的
        List<Long> searchIds = attrService.getSearchAttrIds(attrIds);

        // 再通过 查到的 searchIds 到 pms_product_attr_value 查询
        List<ProductAttrValueEntity> searchEntities = attrValueService
                .list(new QueryWrapper<ProductAttrValueEntity>().in("attr_id", searchIds));

        List<SkuEsModel.Attrs> attrsList = searchEntities.stream().map((item) -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        //1.1 查出 相关 spu的 所有 sku
        List<SkuInfoEntity> skuList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        // 是否有库存 调用 仓库微服务
        List<Long> longs = skuList.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

        // 有可能远程调用失败
        List<SkuHasStock> skuHasStock=null;
        try{
             skuHasStock = wareFeignService.getSkuHasStock(longs);

        }catch (Exception e){
            log.error("调用仓库服务失败");
        }


        List<SkuHasStock> finalSkuHasStock = skuHasStock;
        List<SkuEsModel> skuEsModelList = skuList.stream().map((item) -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            // 完成属性对拷
            BeanUtils.copyProperties(item, skuEsModel);
            // price ,img
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setBrandImg(item.getSkuDefaultImg());

            //hotScore
            skuEsModel.setHotScore(0l);
            //   hasStock
            if(finalSkuHasStock ==null){
                skuEsModel.setHasStock(true);
            }else{

                Map<Long, Boolean> map = finalSkuHasStock.stream().collect(Collectors.toMap(SkuHasStock::getSkuId, SkuHasStock::isHasStock));
              skuEsModel.setHasStock(map.get(item.getSkuId()));
            }
            // brandName brandImg
            BrandEntity brand = brandService.getById(item.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setSkuImg(brand.getLogo());

            //catalogName
            CategoryEntity entity = categoryService.getById(item.getCatalogId());
            skuEsModel.setCatalogName(entity.getName());


            //attrs
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());


        // TODO 传入 es中
        boolean flag = searchFeignService.productStatusUp(skuEsModelList);
        if(flag){
            // 修改商品 的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.ProductEnum.SPU_UP.getCode());
        }else{
              // TODO 接口幂等性
        }
    }


    /**
     * 获得商品 的详情信息
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo getSkuItemDetail(Long skuId) throws ExecutionException, InterruptedException {

        SkuItemVo  skuItemVo=new SkuItemVo();
        // 获得 sku 的基本信息
        CompletableFuture<SkuInfoEntity> future = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
            skuItemVo.setInfo(skuInfo);
            return skuInfo;
        },threadPoolExecutor);



        // 获得 sku的图片信息
        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> imagesEntities = skuImagesService
                    .list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            skuItemVo.setImages(imagesEntities);
        }, threadPoolExecutor);


        //  获取 所有 的销售属性  通过 spuid查询出所有相关的 sku信息
        CompletableFuture<Void> saleAttrsFuture = future.thenAcceptAsync((res) -> {
            List<SkuItemSaleAttrVo> saleAttr = skuSaleAttrValueService.getAllSkuBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttr);
        },threadPoolExecutor);
        //  获取 spu  描述信息
        CompletableFuture<Void> spuInfoDescFuture = future.thenAcceptAsync((res) -> {
            SpuInfoDescEntity descEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(descEntity);
        },threadPoolExecutor);
        // 获取 spu属性分组信息
        CompletableFuture<Void> attrGroups = future.thenAcceptAsync((res) -> {
            List<SpuItemAttrGroupVo> groupAttrs = baseMapper.getSpuCategoryInfo(res.getCatalogId(), res.getSpuId());
            skuItemVo.setGroupAttrs(groupAttrs);
        }, threadPoolExecutor);

       // 所有完成 后 返回结果
        CompletableFuture.allOf(saleAttrsFuture,spuInfoDescFuture,attrGroups,imagesFuture).get();
        return skuItemVo;
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity infoEntity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = getById(infoEntity.getSpuId());
        return spuInfoEntity;
    }


}